# SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
# SPDX-License-Identifier: Mulan PSL v2
# 记录原来的环境变量，安装完成后，需要恢复环境变量
OLD="${PATH}"
CURRENT_PWD="$(cd `dirname $0`; pwd)"

# 进入lib目录, 并解压 node yarn sfx2 工具
cd lib
tar -xzf node-v10.15.0-linux-x64.tar.gz
tar -xzf yarn-0.21.3-linux-x86_64.tar.gz
tar -xzf sfx-v2.3.3.tar.gz
cd ..

# sfx目录名称
SFX2="sfx-v2.3.3"

# 添加环境变量
echo "add lib to path. node, npm, yarn, sfx..."
NEW="${CURRENT_PWD}/lib/node-v10.15.0-linux-x64/bin/:${PATH}"
export PATH=${NEW}
NEW="${CURRENT_PWD}/lib/yarn-0.21.3-linux-x86_64/bin/:${PATH}"
export PATH=${NEW}
NEW="${CURRENT_PWD}/lib/${SFX2}/bin/:${PATH}"
export PATH=${NEW}

function reset_env
{
    # 还原环境变量
    echo "reset env path"
    export PATH="${OLD}"
}

# 添加可执行权限
echo "chmod node, npm, phantomjs"
chmod +x ./lib/node-v10.15.0-linux-x64/bin/*
chmod +x ./lib/node-v10.15.0-linux-x64/lib/node_modules/npm/bin/*
rm -rf ./lib/node-v10.15.0-linux-x64/bin/npm
ln -s ../lib/node_modules/npm/bin/npm-cli.js ./lib/node-v10.15.0-linux-x64/bin/npm
chmod +x ./lib/yarn-0.21.3-linux-x86_64/bin/*
chmod +x ./lib/${SFX2}/bin/*

# 清除缓存
echo "yarn cache clean"
yarn cache clean

# 安装项目
echo "install dependencies of sfx"
cd ./lib/sfx-v2.3.3
yarn install
npm link --force
cd ../../
if [ $? -ne 0 ]; then
    echo "[project] yarn install error!"
    reset_env;
    exit 1
fi

reset_env;
